package com.esun.payment_api.security.handler;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.esun.common.constant.HttpStatus;
import com.esun.common.utils.JWTUtils;
import com.esun.common.utils.ServletUtils;
import com.esun.common.utils.StringUtils;
import com.esun.payment_api.security.AjaxResult;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;

/**
 * 认证失败处理类 返回未授权或具体的token解析问题
 * 
 * @author yzd
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint, Serializable
{
    private static final long serialVersionUID = -8970718410437077606L;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e)
            throws IOException
    {
        int code = HttpStatus.FORBIDDEN;
        String msg = StringUtils.format("请求访问：{}，认证失败，无法访问系统资源", request.getRequestURI());
        try {
            JWTUtils.verify(JWTUtils.getToken(request));
        } catch (SignatureVerificationException exception){
            exception.printStackTrace();
            code = HttpStatus.FORBIDDEN;
            msg = "无效签名";
        } catch (JWTDecodeException exception){
            exception.printStackTrace();
            code = HttpStatus.FORBIDDEN;
            msg = "token解析失败";
        } catch (TokenExpiredException exception){
            exception.printStackTrace();
            code = HttpStatus.FORBIDDEN;
            msg = "token过期";
        } catch (AlgorithmMismatchException exception){
            exception.printStackTrace();
            code = HttpStatus.FORBIDDEN;
            msg = "token签名算法不一致";
        } catch (Exception exception){
            exception.printStackTrace();
        } finally {
            ServletUtils.renderString(response, JSON.toJSONString(AjaxResult.error(code, msg)));
        }
    }
}
